package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.ragflow.DocumentData;
import com.docmgmt.mvp.ragflow.RAGFlowClient;
import com.docmgmt.mvp.ragflow.dto.UpdateDocumentRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * RAGFlow 文档管理 Controller
 *
 * 提供文档删除、更新、停止解析等接口
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ragflow/datasets/{datasetId}")
@RequiredArgsConstructor
@Tag(name = "RAGFlow 文档管理", description = "RAGFlow 文档删除、更新、停止解析接口")
public class RAGFlowDocumentController {

    private final RAGFlowClient ragFlowClient;

    /**
     * 删除文档
     *
     * DELETE /api/v1/ragflow/datasets/{datasetId}/documents
     *
     * @param datasetId   知识库ID
     * @param requestBody 请求体，包含ids数组
     * @return 删除结果
     */
    @DeleteMapping("/documents")
    @PreAuthorize("hasAuthority('ragflow:doc:delete')")
    @Operation(summary = "删除文档", description = "批量删除知识库中的文档")
    public Result<Void> deleteDocuments(
            @PathVariable String datasetId,
            @Valid @RequestBody Map<String, List<String>> requestBody) {
        try {
            List<String> documentIds = requestBody.get("ids");

            if (documentIds == null || documentIds.isEmpty()) {
                return Result.error("文档ID列表不能为空");
            }

            log.info("收到删除文档请求: dataset_id={}, document_ids={}", datasetId, documentIds);
            ragFlowClient.deleteDocuments(datasetId, documentIds);
            log.info("文档删除成功: dataset_id={}, count={}", datasetId, documentIds.size());
            return Result.success("文档删除成功");
        } catch (Exception e) {
            log.error("删除文档失败: dataset_id={}", datasetId, e);
            return Result.error("删除文档失败: " + e.getMessage());
        }
    }

    /**
     * 更新文档配置
     *
     * PUT /api/v1/ragflow/datasets/{datasetId}/documents/{documentId}
     *
     * @param datasetId  知识库ID
     * @param documentId 文档ID
     * @param request    更新请求
     * @return 更新后的文档信息
     */
    @PutMapping("/documents/{documentId}")
    @PreAuthorize("hasAuthority('ragflow:doc:update')")
    @Operation(summary = "更新文档配置", description = "更新文档名称、chunk_method、parser_config等配置")
    public Result<DocumentData> updateDocument(
            @PathVariable String datasetId,
            @PathVariable String documentId,
            @Valid @RequestBody UpdateDocumentRequest request) {
        try {
            log.info("收到更新文档配置请求: dataset_id={}, document_id={}", datasetId, documentId);
            DocumentData updatedDoc = ragFlowClient.updateDocument(datasetId, documentId, request);
            log.info("文档配置更新成功: dataset_id={}, document_id={}", datasetId, documentId);
            return Result.success(updatedDoc);
        } catch (Exception e) {
            log.error("更新文档配置失败: dataset_id={}, document_id={}", datasetId, documentId, e);
            return Result.error("更新文档配置失败: " + e.getMessage());
        }
    }

    /**
     * 停止文档解析
     *
     * DELETE /api/v1/ragflow/datasets/{datasetId}/chunks
     *
     * @param datasetId   知识库ID
     * @param requestBody 请求体，包含document_ids数组
     * @return 停止结果
     */
    @DeleteMapping("/chunks")
    @PreAuthorize("hasAuthority('ragflow:doc:update')")
    @Operation(summary = "停止文档解析", description = "停止指定文档的解析任务")
    public Result<Void> stopDocumentParsing(
            @PathVariable String datasetId,
            @Valid @RequestBody Map<String, List<String>> requestBody) {
        try {
            List<String> documentIds = requestBody.get("document_ids");

            if (documentIds == null || documentIds.isEmpty()) {
                return Result.error("文档ID列表不能为空");
            }

            log.info("收到停止文档解析请求: dataset_id={}, document_ids={}", datasetId, documentIds);
            ragFlowClient.stopDocumentParsing(datasetId, documentIds);
            log.info("文档解析停止成功: dataset_id={}, count={}", datasetId, documentIds.size());
            return Result.success("文档解析停止成功");
        } catch (Exception e) {
            log.error("停止文档解析失败: dataset_id={}", datasetId, e);
            return Result.error("停止文档解析失败: " + e.getMessage());
        }
    }
}

